package com.freedy.concurrent.JMM.pattrens;

import com.freedy.concurrent.Monitors.Sleeper;
import lombok.extern.slf4j.Slf4j;


/**
 * 两阶段暂停模式的改进
 * @author Freedy
 * @date 2021/4/23 15:38
 */
@Slf4j
public class TwoStageTermination {
    public volatile boolean isInterrupted = false;
    public boolean starting = false;

    public static void main(String[] args) throws Exception {
        TwoStageTermination termination = new TwoStageTermination();
        for (int i = 0; i < 500; i++) {
            new Thread(termination::start).start();
        }
        Sleeper.sleep(3.5);
        termination.stop();

    }

    //启动监控线程
    public void start() {
        synchronized (this) {
            if (starting) {
                return;
            }
            starting = true;
        }
        isInterrupted = false;
        new Thread(() -> {
            while (true) {
                if (isInterrupted) {
                    //释放资源
                    log.debug("释放资源");
                    break;
                }
                try {
                    Thread.sleep(500);
                    //your code hear...
                    log.debug("执行监控记录");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //停止监控线程
    public void stop() {
        isInterrupted = true;
        starting = false;
    }

}
